// Copyright (C) 2008 Taylor L. Riche <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//

#include "ProcElement.h"

namespace lagniappe
{

ProcElement::ProcElement(bool profile = false) : freeze(false), inProfile(profile)
{
}

ProcElement::~ProcElement()
{
}

RCon *
ProcElement::getProfRCon()
{
	RCon * ret = profQueue.front();
	profQueue.pop();
	return ret;
}

void
ProcElement::putProfRCon(RCon * rcon)
{
	profQueue.push(rcon);
}

void
ProcElement::process() 
{
	// Test for profiling
	//std::cerr << ((inProfile)?("True"):("False")) << std::endl;
	if(inProfile) {
		//while(true) {
			this->profileLock();
			while(profQueue.size() < PROF_SIZE && inProfile) {
				this->profileWait();
			}
			while(!profQueue.empty()) {
				RCon * curr = getProfRCon();
				curr->getOp()->processRequest(curr);
			}
			std::cerr << "Done" << std::endl;
			this->profileNotify();
			this->profileUnlock();
		//}
	}
	else {
		// Main processing loop
		while(true) {
			RCon * curr = this->getRCon();
			curr->getOp()->processRequest(curr);
		}
	}
}

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

void * 
startProc(void * arg)
{

//  ** OLD TEMPLATE BASED CODE **	
//  MethodWrapper<ProcElement> * mw = static_cast<MethodWrapper<ProcElement> *>(arg);
//  ProcElement* obj = mw->object;
//  void(ProcElement::*mthd)() = mw->method;
//  delete mw;
//  (obj->*mthd)();
//  return NULL;
//  ** OLD TEMPLATE BASED CODE **	

	ProcElement * proc = static_cast<ProcElement *>(arg);
	proc->process();
	return NULL;
}

#ifdef __cplusplus
}
#endif /* __cplusplus */

}
